package top.hkyzf.study.datastructure.sparsearray;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 稀疏数组（从硬盘还原稀疏数组）
 * @author 朱峰
 * @date 2020-12-17 13:28
 */
public class SparseArrayFromDisk {
    public static void main(String[] args) {
        // 1. 从硬盘读取保存的稀疏数组。
        int [][] sparseArray = readFile();

        // 2. 还原为原数组
        int [][] chessArrayNew = new int[sparseArray[0][0]][sparseArray[0][1]];
        for(int i=1; i<sparseArray.length; i++) {
            chessArrayNew[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        System.out.println("还原后的数组为：");
        printArray(chessArrayNew);

    }

    // 输出数组结果
    private static void printArray(int [][] arrays) {
        for(int i=0; i<arrays.length; i++) {
            for(int j=0; j<arrays[i].length; j++) {
                if(j == arrays[i].length-1) {
                    System.out.printf("%d", arrays[i][j]);
                } else {
                    System.out.printf("%d\t", arrays[i][j]);
                }
            }
            System.out.println();
        }
    }

    // 从本地硬盘读取sparse.data文件到内存
    private static int [][] readFile() {
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        int [][] sparseArray =  null;

        try {
            fis = new FileInputStream(SparseArrayFromDisk.class.getResource("/").getPath() + "sparse.data");
            isr = new InputStreamReader(fis, "UTF-8");
            br = new BufferedReader(isr);
            List<String> list = new ArrayList<>();
            String line = "";
            while ((line = br.readLine()) != null) {
                list.add(line);
            }
            sparseArray = new int[list.size()][3];
            for(int i=0; i<list.size(); i++) {
                String [] array = list.get(i).replace("[", "").replace("]", "").split(",");
                for(int j=0; j<array.length; j++) {
                    sparseArray[i][j] = Integer.valueOf(array[j].trim());
                }
            }

            System.out.println("读取文件并转换完成！");
            printArray(sparseArray);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(br != null) {
                    br.close();
                }
                if(isr != null) {
                    isr.close();
                }
                if(fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sparseArray;
    }
}
